import http.client
import urllib.parse
import json
class GetAudio():
    #替换为自己的阿里云语言识别appKey和token
    appKey = '*******'
    token = '*******'
    text = ''
    audioSaveFile = 'results.wav'
    format = 'wav'
    sampleRate = 16000

    def __init__(self,text):
        self.text = text

    def processGETRequest(self):
        # 采用RFC 3986规范进行urlencode编码。
        textUrlencode = self.text
        textUrlencode = urllib.parse.quote_plus(textUrlencode)
        textUrlencode = textUrlencode.replace("+", "%20")
        textUrlencode = textUrlencode.replace("*", "%2A")
        textUrlencode = textUrlencode.replace("%7E", "~")
        host = 'nls-gateway.cn-shanghai.aliyuncs.com'
        url = 'https://' + host + '/stream/v1/tts'
        # 设置URL请求参数
        url = url + '?appkey=' + self.appKey
        url = url + '&token=' + self.token
        url = url + '&text=' + self.text
        url = url + '&format=' + self.format
        url = url + '&sample_rate=' + str(self.sampleRate)
        # voice 发音人，可选，默认是xiaoyun。
        # url = url + '&voice=' + 'xiaoyun'
        # volume 音量，范围是0~100，可选，默认50。
        # url = url + '&volume=' + str(50)
        # speech_rate 语速，范围是-500~500，可选，默认是0。
        # url = url + '&speech_rate=' + str(0)
        # pitch_rate 语调，范围是-500~500，可选，默认是0。
        # url = url + '&pitch_rate=' + str(0)
        print(url)
        # Python 2.x请使用httplib。
        # conn = httplib.HTTPSConnection(host)
        # Python 3.x请使用http.client。
        conn = http.client.HTTPSConnection(host)
        conn.request(method='GET', url=url)
        # 处理服务端返回的响应。
        response = conn.getresponse()
        print('Response status and response reason:')
        print(response.status, response.reason)
        contentType = response.getheader('Content-Type')
        print(contentType)
        body = response.read()
        if 'audio/mpeg' == contentType:
            with open(self.audioSaveFile, mode='wb') as f:
                f.write(body)
            print('The GET request succeed!')
            conn.close()
            return True
        else:
            print('The GET request failed: ' + str(body))
            conn.close()
            return False

    def processPOSTRequest(self):
        host = 'nls-gateway.cn-shanghai.aliyuncs.com'
        url = 'https://' + host + '/stream/v1/tts'
        # 设置HTTPS Headers。
        httpHeaders = {
            'Content-Type': 'application/json'
        }
        # 设置HTTPS Body。
        body = {'appkey': self.appKey, 'token': self.token, 'text': self.text, 'format': self.format, 'sample_rate': self.sampleRate}
        body = json.dumps(body)
        print('The POST request body content: ' + body)
        # Python 2.x请使用httplib。
        # conn = httplib.HTTPSConnection(host)
        # Python 3.x请使用http.client。
        conn = http.client.HTTPSConnection(host)
        conn.request(method='POST', url=url, body=body, headers=httpHeaders)
        # 处理服务端返回的响应。
        response = conn.getresponse()
        print('Response status and response reason:')
        print(response.status, response.reason)
        contentType = response.getheader('Content-Type')
        print(contentType)
        body = response.read()
        if 'audio/mpeg' == contentType:
            with open(self.audioSaveFile, mode='wb') as f:
                f.write(body)
            print('The POST request succeed!')
            conn.close()
            return True
        else:
            print('The POST request failed: ' + str(body))
            conn.close()
            return False
